import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import {NzNotificationService} from "ng-zorro-antd";
import {HttpServcie} from "../../../../service/http.service";
import {ElevatorInfoBean} from "../bean/elevatorInfo.bean";

import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import {FileUploader, FileItem, ParsedResponseHeaders} from "ng2-file-upload";
import {Config} from "../../../../service/config";
import {elevatorPlaces} from "../../../../service/constant/elevatorPlaceConstant";
import {PartyBean} from "../../../user/party/bean/party.bean";

@Component({
  selector: "elevator-batch-modify",
  templateUrl: "elevator-batch-modify.html",
  styleUrls: ["elevator-batch-modify.scss"]
})
/**
 * 电梯信息批量修改
 */
export class ElevatotBatchModifyPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  expandDataCache = {};
  @Input()
  inValue: any = {};
  data = [];
  @Output("outPut")
  outPut = new EventEmitter();
  //电梯信息
  elevatorInfoBean: ElevatorInfoBean = new ElevatorInfoBean();
  elevatorInfoList: any = [];

  noticeMessage: string;
  //电梯添加的权限(功能)
  funList: any = [];
  flag: boolean = true;
  //机构的集合
  partyList: any = [];
  //省市区
  options: any = [];
  //地址
  addresOptions: any = [];
  //电梯类型
  elevatorTypeOptions: any = [];
  //物业
  wuyeList: any = [];
  //维保
  weibaoList: any = [];
  // 检验
  jianyanList: any = [];
  // 监管
  jianguanList: any = [];
  // 检验人员
  jianyanren: any = [];
  //安全管理人员
  anquanList: any = [];
  //维保人员
  weibaoren: any = [];
  // 电梯场所类型
  elevatorPlaces = elevatorPlaces;
  initCheckDate: any;
  showImage: any = [];
  config: any = Config;

  // 返回使用单位列表
  public userPartyList:any=[];
  // 返回维保单位列表
  public maintenancePartyList:any=[];

  // 单位实体
  partyBean: PartyBean = new PartyBean();
  //
  partyBeanNew: PartyBean = new PartyBean();
  // 单位类型
  public partyType:any="";
  // 获取维保单位的选择id
  public maintenance:any;
  // 定义使用单位
  public userBy:any;

  // 定义维保人员1
  public maintenance1:any;
  // 定义维保人员2
  public maintenance2:any;
  public flagType:boolean = true;


  fileUploader = new FileUploader({
    url: Config.IP + Config.API.upload,
    method: "POST",
    itemAlias: "file",
    autoUpload: false,
    headers: [
      {name: "Authorization", value: "Bearer " + window.localStorage["token"]}
    ]
  });

  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) {
  }

  /**
   * 选择checkbox
   * @param event
   * @param param
   */
  refreshStatus(event, param) {
    if (event) {
      this.funList.push(param);
    } else {
      //如果非选中状态移除
      if (this.funList.length > 0) {
        this.httpServcie.removeByValue(this.funList, param);
      }
    }
  }

  ngOnInit() {

    let partyTypeId = JSON.parse(window.localStorage.getItem("user")).partyType;
    this.partyType = partyTypeId;
    this.partyBean = JSON.parse(window.localStorage.getItem("user"));

    let parentId = "";
    if (partyTypeId == "4") {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyId;
    } else {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
    }

    this.validateForm = this.fb.group({
      elevatorNum: [null, [Validators.required]],
      serialNum: [null, [Validators.required]],
      addresOptions: [null, [Validators.required]],
      elevatorStreet: [null, [Validators.nullValidator]],
      elevatorAddr: [null, [Validators.nullValidator]],
      elevatorModel: [null, [Validators.nullValidator]],
      elevatorTypeId: [null, [Validators.nullValidator]],
      elevatorPhotoUrl: [null, [Validators.nullValidator]],
      examinationPartyName: [null, [Validators.nullValidator]],
      usedPartyId: [null, [Validators.nullValidator]],
      buildingInfo: [null, [Validators.nullValidator]],
      elevatorBuildingNum: [null, [Validators.nullValidator]],
      createCompanyName: [null, [Validators.nullValidator]],
      examinationPartyId: [null, [Validators.nullValidator]],
      nextCheckDateShow: [null, [Validators.nullValidator]],
      safeUserId: [null, [Validators.nullValidator]],
      maintenanceUserFirst: [null, [Validators.required]],
      maintenanceUserSecond: [null, [Validators.required]],
      rescuePhoneNum: [null, [Validators.nullValidator]],
      insuranceNum: [null, [Validators.nullValidator]],
      lastMaintenanceTimeShow: [null, [Validators.nullValidator]],
      isStop: [null, [Validators.nullValidator]],
      nextMaintenanceDateShow: [null, [Validators.nullValidator]],
      pointsNum: [null, [Validators.nullValidator]],
      qrCodeUrl: [null, [Validators.nullValidator]],
      insuranceName: [null, [Validators.nullValidator]],
      insuranceDateShow: [null, [Validators.nullValidator]],
      maintTel: [null, [Validators.nullValidator]],
      nextHalfmonMaintDateShow: [null, [Validators.nullValidator]],
      nextQuarterlyMainteDateShow: [null, [Validators.nullValidator]],
      nextHalfyearMaintDateShow: [null, [Validators.nullValidator]],
      nextYearMaintDateShow: [null, [Validators.nullValidator]],
      outsideNum: [null, [Validators.nullValidator]],
      maintenancePartyId: [null, [Validators.nullValidator]],
      buildAddr: [null, [Validators.nullValidator]],
      usedNum: [null, [Validators.nullValidator]],
      beUsedDateShow: [null, [Validators.nullValidator]],
      governorCkDateShow: [null, [Validators.nullValidator]],
      floorStation: [null, [Validators.nullValidator]],
      safeUserTel: [null, [Validators.nullValidator]],
      buildPartyName: [null, [Validators.nullValidator]],
      ratedLoad: [null, [Validators.nullValidator]],
      runSpeed: [null, [Validators.nullValidator]],
      angle: [null, [Validators.nullValidator]],
      stepWidth: [null, [Validators.nullValidator]],
      liftHeight: [null, [Validators.nullValidator]],
      driveWay: [null, [Validators.nullValidator]],
      brandName: [null, [Validators.nullValidator]],
      elevatorPlace: [null, [Validators.nullValidator]],
      branchOffice: [null, [Validators.required]],
      programName: [null, [Validators.nullValidator]],
      lastInspectDateShow: [null, [Validators.nullValidator]],
      innerId: [null, [Validators.nullValidator]],
      examinationUserFirst: [null, [Validators.nullValidator]],
      examinationUserSecond: [null, [Validators.nullValidator]]
    });
    if (this.inValue) {
      this.initCheckDate = this.inValue.nextCheckDate;
      let eleValue = Object.assign([], this.inValue);
      this.elevatorInfoList = eleValue;
    }

    //根据维保单位查询维保人员

    if (
      undefined != this.elevatorInfoList[0].maintenancePartyId &&
      null != this.elevatorInfoList[0].maintenancePartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorInfoList[0].maintenancePartyId)
        .subscribe(data => {
          if (data.status == 200) {
            this.weibaoren = data.data;

            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "7") {
                  this.weibaoren.push(user);
                }
              });
            }
          }
        });
    }

    // 初始化使用单位
    this.findUserPartyList();

    // 初始化维保单位
    this.findMaintenancePartyList();

  }

  ngOnChanges() {

  }

  doSubmin($event) {
    // 维保人员未选择，或维保人员相同 不可以提交
    for (let i = 0; i < this.elevatorInfoList.length; i++) {
      this.elevatorInfoBean = this.elevatorInfoList[i];
      // 维保单位登录 不能修改使用单位，可以修改维保人员
      if (this.partyType == "1") {
        if ((this.maintenance1 == undefined || this.maintenance1 == '') || (this.maintenance2 == undefined || this.maintenance2 == '')) {
          this._notification.create("warning", "警告提示", "维保人员不能为空，请重新选择！");
          return false;
        }
        if (this.maintenance1 == this.maintenance2) {
          this._notification.create("warning", "警告提示", "维保人员不能相同，请重新选择！");
          return false;
        }
        this.elevatorInfoBean.maintenanceUserFirst = this.maintenance1;
        this.elevatorInfoBean.maintenanceUserSecond = this.maintenance2;
      }
      //使用单位登录  当维保单位为空时则不进行修改，它还可以修改使用单位
      if (this.partyType == "2") {
        if (this.maintenance != undefined && this.maintenance != "") {
          this.elevatorInfoBean.maintenancePartyId = this.maintenance;
          if ((this.maintenance1 == undefined || this.maintenance1 == '') || (this.maintenance2 == undefined || this.maintenance2 == '')) {
            this._notification.create("warning", "警告提示", "维保人员不能为空，请重新选择！");
            return false;
          }
          if (this.maintenance1 == this.maintenance2) {
            this._notification.create("warning", "警告提示", "维保人员不能相同，请重新选择！");
            return false;
          }
          this.elevatorInfoBean.maintenanceUserFirst = this.maintenance1;
          this.elevatorInfoBean.maintenanceUserSecond = this.maintenance2;
        }
        if (this.userBy != undefined && this.userBy != "") {
          this.elevatorInfoBean.usedPartyId = this.userBy;
        }
      }
      this.submitForm($event);
    }
    this._notification.create("success", "成功提示", "修改成功");
    this.outPut.emit($event);
  }

  submitForm($event) {
    //this.elevatorInfoBean.parentId = JSON.parse(window.localStorage['user']).partyId;
    let ob = this.httpServcie.elevatorUpdate(this.elevatorInfoBean);
    ob.subscribe(data => {
      this.isSpinning = false;
      if (data.status !== 200) {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  executeArray(items, res: any) {
    items.map(item => {
      if (item.checked) {
        res.push({name: item.text, id: item.value});
      }
      if (item.childList) {
        this.executeArray(item.childList, res);
      }
    });

    return res;
  }

  collapse(array, data, $event) {
    if ($event === false) {
      if (data.childList) {
        data.childList.forEach(d => {
          const target = array.find(a => a.authorId === d.authorId);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [],
      array = [],
      hashMap = {};
    stack.push({...root, level: 0, expand: false});

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.childList) {
        for (let i = node.childList.length - 1; i >= 0; i--) {
          stack.push({
            ...node.childList[i],
            level: node.level + 1,
            expand: false,
            parent: node
          });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.authorId]) {
      hashMap[node.authorId] = true;
      array.push(node);
    }
  }

  /** load data async  */
  loadData(e: {
    option: any;
    index: number;
    resolve: Function;
    reject: Function;
  }): void {
    if (e.index === -1) {
      e.resolve(this.httpServcie.getProvince());
      return;
    }

    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      let values: any = option["value"];
      let valueList = this.httpServcie.getCity(e.option);
      let cities: any = {};
      cities[values] = valueList;

      setTimeout(() => {
        option.loading = false;
        e.resolve(cities[option.value]);
      }, 1);
    }
    if (e.index === 1) {
      let value = option["value"];
      let valueList = this.httpServcie.getRelation(e.option);
      let scenicspots: any = {};
      scenicspots[value] = valueList;
      setTimeout(
        () => {
          option.loading = false;
          e.resolve(scenicspots[option.value]);
        },
        1,
        scenicspots,
        option
      );
    }
  }

  /**
   * 查询维保单位
   */
  public findMaintenancePartyList() {
    this.partyBeanNew.partyType = "1";
    this.partyBeanNew.id =JSON.parse(window.localStorage.getItem("user")).partyParentId;
    this.httpServcie.queryByIdAndTypeList(this.partyBeanNew).subscribe(data => {
      if (data.status == 200) {
        this.maintenancePartyList = data.data;
        console.log(data.data);
      }
    });
  }
  /**
   * 查询使用单位
   */
  public findUserPartyList() {
    this.partyBeanNew.partyType = "2";
    this.httpServcie.queryByIdAndTypeList(this.partyBeanNew).subscribe(data => {
      if (data.status == 200) {
        this.userPartyList = data.data;
        console.log(data.data);
      }
    });
  }

  // 维保单位改变,维保人员进行改变
  getChange() {
    this.httpServcie.queryUserByPartyId(this.maintenance).subscribe(data => {
      if (data.status == 200) {
        this.weibaoren = [];

        console.log(data.data);
        if (data.data && data.data.length > 0) {
          data.data.forEach(user => {
            if (user.type == "user" && user.roleId == "7") {
              this.weibaoren.push(user);
            }
          });
        }
      }
    });
  }
}
